﻿<MudPopoverProvider />

<MudGrid>
    <MudItem xs="12">
        <MudSelect T="Coffee" Label="Coffee"
                   MultiSelection="true"
                   SelectedValues="_selected" SelectedValuesChanged="SelectedChanged"
                   Comparer="Comparer"
                   ToStringFunc="@(x => x?.Name)">
            <MudSelectItem Value="@(new Coffee("cap","Cappuccino"))" />
            <MudSelectItem Value="@(new Coffee("lat","Cafe Latte"))" />
            <MudSelectItem Value="@(new Coffee("esp","Espresso"))" />
            <MudSelectItem Value="@(new Coffee("ire","Irish Coffee"))" />
        </MudSelect>
    </MudItem>
    <MudItem xs="12">
        <MudButton id="set-selection-button" OnClick="SetSelection">Set Selection</MudButton>
    </MudItem>
</MudGrid>

@code {
    private static CoffeeComparer Comparer { get; } = new();

    private readonly HashSet<Coffee?> _selected = new(Comparer);

    private void SelectedChanged(IEnumerable<Coffee?>? newSelected)
    {
        _selected.Clear();
        if (newSelected is not null)
        {
            _selected.UnionWith(newSelected);
        }
    }

    private void SetSelection()
    {
        _selected.Clear();
        _selected.Add(new Coffee("lat", "Selected Cafe Latte"));
        _selected.Add(new Coffee("esp", "Selected Espresso"));
    }

    private class Coffee(string key, string name)
    {
        public string Key { get; } = key;
        public string Name { get; } = name;
    }

    private class CoffeeComparer : IEqualityComparer<Coffee?>
    {
        public bool Equals(Coffee? a, Coffee? b) => a?.Key == b?.Key;

        public int GetHashCode(Coffee? x) => HashCode.Combine(x?.Key);
    }
}
